package com.ngkj.zmfptback.sys.controller;

import cn.hutool.Hutool;
import cn.hutool.core.lang.UUID;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.ngkj.zmfptCommon.common.bean.CommonReslut;
import com.ngkj.zmfptCommon.common.sftp.SFTPChannel;
import com.ngkj.zmfptCommon.common.sftp.SFTPConstants;
import com.ngkj.zmfptCommon.common.util.ResultEnum;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ChenHN
 * @since 2021/11/25 creation
 **/
@RestController
public class FileUploadController {

    @Resource
    private SFTPChannel sftpChannel;

    @PostMapping("/saveTalkingFile")
    public CommonReslut<String> saveTalkingFile( MultipartFile file) throws JSchException, SftpException, IOException {
        try {
            Map<String, String> connectParameter = SFTPConstants.getConnectParameter();
            ChannelSftp channel = sftpChannel.getChannel(connectParameter, SFTPConstants.TIMEOUT);
            StringBuilder dir = new StringBuilder( "/usr/local/static/images/messageFile");
            String time = new SimpleDateFormat("yyyyMMdd").format(new Date());
            StringBuilder append = dir.append("/" + time);
            SftpATTRS attrs = null;
            try {
                attrs = channel.stat(dir.toString());
            } catch (SftpException e) {
                // TODO: 2022/1/27
            }
            if (ObjectUtils.isEmpty(attrs)){
                channel.mkdir(dir.toString());
            }
            String originalFilename = file.getOriginalFilename();
            String filePath = dir + "/" +UUID.randomUUID().toString().replace("-","") + "_" +originalFilename;
            channel.put(file.getInputStream(),filePath,ChannelSftp.OVERWRITE);
            String[] split = filePath.split("/static");
            return new CommonReslut<>(ResultEnum.ok,split[1]);
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonReslut<>(ResultEnum.error);
    }

}
